
clear
set more off


insheet using state_fips_cross_walk.csv, comma
sort ptstate
save state_fips_crosswalk, replace
clear

use state_pop_2008
sort fips
save, replace
clear

forvalues i=7/10 {
forvalues j=1/4 {
if `i'<10 { 
use "C:\Users\wevans1\Google Drive\opioids\florida_data\emergency_department\stata_data_files\ED0`i'Q`j'.DTA"
}
else {
use "C:\Users\wevans1\Google Drive\opioids\florida_data\emergency_department\stata_data_files\ED`i'Q`j'.DTA"
}

gen opp=prindiag=="965.00" | prindiag=="965.02" | prindiag=="965.09"
gen op1=OTHDIAG1=="965.00" | OTHDIAG1=="965.02" | OTHDIAG1=="965.09"
gen op2=OTHDIAG2=="965.00" | OTHDIAG2=="965.02" | OTHDIAG2=="965.09"
gen op3=OTHDIAG3=="965.00" | OTHDIAG3=="965.02" | OTHDIAG3=="965.09"
gen op4=OTHDIAG4=="965.00" | OTHDIAG4=="965.02" | OTHDIAG4=="965.09"
gen op5=OTHDIAG5=="965.00" | OTHDIAG5=="965.02" | OTHDIAG5=="965.09"
gen op6=OTHDIAG6=="965.00" | OTHDIAG6=="965.02" | OTHDIAG6=="965.09"
gen op7=OTHDIAG7=="965.00" | OTHDIAG7=="965.02" | OTHDIAG7=="965.09"
gen op8=OTHDIAG8=="965.00" | OTHDIAG8=="965.02" | OTHDIAG8=="965.09"
gen op9=OTHDIAG9=="965.00" | OTHDIAG9=="965.02" |  OTHDIAG9=="965.09"
gen ec1=ECODE1=="E850.2" | ECODE1=="e850.1"
gen ec2=ECODE2=="E850.2" | ECODE2=="e850.1"
gen ec3=ECODE3=="E850.2" | ECODE3=="e850.1"
gen opioid_admit=max(opp,op1,op2,op3,op4,op5,op6,op7,op8,op9,ec1,ec2,ec3)
tab opioid_admit

gen nonopioid_admit=1-opioid_admit
drop if ptstate=="XX" | ptstate=="FL"
keep year qtr FAC_COUNTY ptstate age sex opioid_admit nonopioid_admit
save ed_admits`i'q`j', replace
}
}


forvalues i=7/9 {
forvalues j=1/4 {
if `i'==7 & `j'==1 {
use ed_admits`i'q`j'
}
else {
append using ed_admits`i'q`j'
}

}
}

append using ed_admits10q1
append using ed_admits10q2

keep if age>=15 & age<=64
sort ptstate
collapse (sum) opioid_admit nonopioid_admit, by(ptstate)

sort ptstate
merge m:1 ptstate using state_fips_crosswalk
drop if _merge~=3
drop if fips==.
drop _merge
sort fips
merge m:1 fips using state_pop_2008
sort fips
keep if _merge==3
drop _merge
outsheet using ed_admits_2.csv, comma replace
